package com.lanou3g.hw0512;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Properties;

@WebServlet(name = "NewsServlet", urlPatterns = "/k")
public class NewsServlet extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf8");
        //获取前端转过来的参数
        String keyWord = request.getParameter("keyWord");


        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            Properties properties= new Properties();
            //使用类名.class.getClassLoader()
//          获取类加载器
            //类加载器的getResourceAsStream
            //是相对于src路径下的
            InputStream is = NewsServlet.class.getClassLoader(

            ).getResourceAsStream("jdbc.properties");
            properties.load(is);
            //创建连接数据库
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/lanou_news",
                    properties);
            String sql = "select * from lanou_news.news where title like ?";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, "%" + keyWord + "%");
            ResultSet rs = statement.executeQuery();
            PrintWriter pw = response.getWriter();

            while (rs.next()) {
                int id = rs.getInt("id");
                String title = rs.getString("title");
                pw.println(id + "-" + title);
                pw.println("<br/>");

            }
            rs.close();
            conn.close();
            statement.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



